package utils;

import com.google.gson.Gson;
import model.Query;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class HttpUtils {

    public static String getRequestBody(HttpServletRequest req) {
        String requestBody = null;
        try (BufferedReader requestReader = req.getReader()){
            StringBuilder string = new StringBuilder();
            String curString;
            while (null != (curString = requestReader.readLine())) {
                string.append(curString);
            }
            requestBody = string.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return requestBody;
    }

    public static Query getQuery(HttpServletRequest req) {
        Set<Map.Entry<String, String[]>> entries = req.getParameterMap().entrySet();
        Query query = new Query(entries.size());
        int i = 0;
        for (Map.Entry<String, String[]> e : entries) {
            query.keys[i] = e.getKey();
            query.values[i] = e.getValue();
        }
        return query;
    }

    @FunctionalInterface
    public interface HttpRequestHandler {
        void handle(HttpServletRequest req, HttpServletResponse resp, Gson gson) throws Exception;
    }

}
